import {costOrders, rollbackSplit, splitPage, splitReject, splitSave} from '../services/dispatch';
import React from 'react';
import {Input, InputNumber, message, Radio, Select, Tooltip} from 'antd';
import {DriverSelect} from '../components/Selection/DriverSelect';

const { Option } = Select;
const { TextArea } = Input

/**
 * 客户数据模型
 */

//表格列表信息
const columns = [
  {
    title: 'load号',
    dataIndex: 'loadNo',
    width: '200px',
    editable: true,
    ellipsis: true,
    fixed: 'left',
    sorter: (a, b) => {
      return a.loadNo.localeCompare(b.loadNo);
    },
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '订单状态',
    dataIndex: 'status',
    width: '100px',
    editable: false,
    ellipsis: true,
    render: text => {
      switch (text) {
        case 'ENTRY':
          return <span>生成</span>;
        case 'SPLIT':
          return <span>拆单</span>;
        case 'SPLITED':
          return <span>拆单完成</span>
        case 'DISPATCH':
          return <span>调度</span>;
        case 'COST_CONFIRMATION':
          return <span>成本确认</span>;
        case 'COST_AUDIT':
          return <span>成本审核</span>;
        case 'ORDER_AUDIT':
          return <span>订单审核</span>;
        case 'LOAD_IN':
          return <span>货物装车</span>;
        case 'LOAD_OFF':
          return <span>货物送达</span>;
        case 'RECEIPT':
          return <span>收到回单</span>;
        case 'COMMON':
          return <span>承运</span>;
        case 'DELIVERY':
          return <span>送达</span>;
        case 'GATHERING':
          return <span>待收款</span>;
        case 'GATHERING_AUDIT':
          return <span>收入审核</span>;
        case 'INVOICE':
          return <span>开票(足额)</span>;
        case 'INVOICE_HALF':
          return <span>开票(足额)</span>;
        case 'FINISH':
          return <span>完成</span>;
        default:
          return <span />;
      }
    },
  },
  {
    title: '业务类型',
    dataIndex: 'busType',
    width: '120px',
    editable: true,
    ellipsis: true,
    render: text => {
      switch (text) {
        case 'LD':
          return <span>零担</span>;
        case 'DC':
          return <span>单程</span>;
        case 'WF':
          return <span>往返</span>;
        default:
          return <span />;
      }
    },
  },
  {
    title: '要车类型',
    dataIndex: 'carType',
    width: '120px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '提货日期',
    dataIndex: 'pickDate',
    width: '140px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '到货日期',
    dataIndex: 'aogDate',
    width: '140px',
    editable: true,
    ellipsis: true,
  },
/*  {
    title: '线路',
    dataIndex: 'line',
    width: '120px',
    editable: true,
    ellipsis: true,
  },*/
  {
    title: '装货工厂',
    dataIndex: 'loadingFactory',
    width: '100px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '卸货工厂',
    dataIndex: 'loadoffFactory',
    width: '100px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '装货地',
    dataIndex: 'loadingPlace',
    width: '200px',
    editable: true,
    ellipsis: true,
    render: (text, record, index) => {
      return (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      );
    },
  },
  {
    title: '卸货地',
    dataIndex: 'loadoffPlace',
    width: '200px',
    editable: true,
    ellipsis: true,
    render: (text, record, index) => {
      return (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      );
    },
  },
  {
    title: '数量',
    dataIndex: 'amount',
    width: '120px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '体积',
    dataIndex: 'volume',
    width: '120px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '重量',
    dataIndex: 'weight',
    width: '120px',
    editable: true,
    ellipsis: true,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    width: '120px',
    editable: true,
    ellipsis: true,
  },
];

// 搜索框字段
const searchFields = [
  {
    cols: [
      {
        md: 6,
        label: 'LOAD号',
        name: 'loadNo',
        component: <TextArea placeholder="请输入LOAD号" />,
      },
      {
        md: 6,
        label: '订单状态',
        name: 'status',
        component: (
          <Select placeholder="请输入订单状态">
            <Option value="SPLIT">拆单</Option>
            <Option value="SPLITED">拆单完成</Option>
            <Option value="DISPATCH">调度</Option>
          </Select>
        ),
      },
      {
        md: 6,
        label: '装货地',
        name: 'loadingPlace',
        component: <Input placeholder="请输入装货地" />,
      },
      {
        md: 6,
        label: '卸货地',
        name: 'loadoffPlace',
        component: <Input placeholder="请输入卸货地" />,
      },
    ],
  },
];

// 校验规则
const requiredCols = {
  load号: [
    {
      required: 'true',
      message: `请输入load号!`,
    },
  ],
  到货日期: [
    {
      required: 'true',
      message: `请输入到货日期!`,
    },
  ],
  提货日期: [
    {
      required: 'true',
      message: `请输入提货日期!`,
    },
  ],
  装货地: [
    {
      required: 'true',
      message: `请输入装货地!`,
    },
  ],
  卸货地: [
    {
      required: 'true',
      message: `请输入卸货地!`,
    },
  ],
  /*
  业务类型: [
    {
      required: 'true',
      message: `请输入业务类型!`,
    },
  ],
  要车类型: [
    {
      required: 'true',
      message: `请输入要车类型!`,
    },
  ],*/
};

// 申请费用表单列
const moneyRows = [
  {
    cols: [
      {
        label: '费用平均方式',
        name: 'avgFlag',
        md: 16,
        rules: [{ required: true, message: '必选' }],
        component: (
          <Radio.Group>
            <Radio.Button value="V">体积</Radio.Button>
            <Radio.Button value="W">重量</Radio.Button>
            <Radio.Button value="Z">整车</Radio.Button>
          </Radio.Group>
        ),
      },
    ],
  },
  {
    cols: [
      {
        label: '实际要车类型',
        name: 'realCarType',
        md: 8,
        component: (
          <Input placeholder="请输入实际要车类型" />
        ),
      },
    ],
  },
  {
    cols: [
      {
        label: '提货费',
        name: 'pickFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入提货费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '干线费',
        name: 'arteryFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入干线费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '送货费',
        name: 'dropoffFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入送货费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '加点费',
        name: 'workoverFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入加点费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '装货费',
        name: 'loadupFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入账号" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '卸货费',
        name: 'loadoffFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入卸货费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '包车费',
        name: 'carFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入包车费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '燃油补助费',
        name: 'fuelFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入燃油补助费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '加班费',
        name: 'callbackFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入加班费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '押车费',
        name: 'escortinFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入押车费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '小费',
        name: 'tipFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入小费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '短驳费',
        name: 'shuttleFee',
        md: 6,
        rules: [{ required: true, message: ' ' }],
        component: <InputNumber placeholder="请输入短驳费" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '司机姓名',
        name: 'driver',
        md: 8,
        rules: [{ required: true, message: ' ' }],
        component: <DriverSelect />,
      },
    ],
  },
  {
    cols: [
      {
        label: '车牌号',
        name: 'carNo',
        md: 8,
        rules: [{ required: true, message: ' ' }],
        component: <Input placeholder="请输入车牌号" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '司机电话',
        name: 'drPhone',
        md: 8,
        rules: [{ required: true, message: ' ' }],
        component: <Input placeholder="请输入司机电话" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '司机身份证',
        name: 'drIdcard',
        md: 8,
        rules: [{ required: true, message: ' ' }],
        component: <Input placeholder="请输入司机身份证" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '账户姓名',
        name: 'accountName',
        md: 8,
        rules: [{ required: true, message: ' ' }],
        component: <Input placeholder="请输入账户姓名" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '银行卡号',
        name: 'bankAccount',
        md: 8,
        rules: [{ required: true, message: ' ' }],
        component: <Input placeholder="请输入银行卡号" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '实际体积',
        name: 'realVoPrice',
        md: 8,
        component:  <InputNumber placeholder="请输入实际体积" />,
      },
    ],
  },
  {
    cols: [
      {
        label: '实际重量',
        name: 'realWePrice',
        md: 8,
        component:  <InputNumber placeholder="请输入实际重量" />,
      },
    ],
  },
];
export default {
  namespace: 'splitOrder',

  state: {
    searchFields: searchFields, // 搜索框信息
    searchValues: {}, // 搜索框里的值
    pageList: [], // 表格数据
    pagination: {
      pageSize: 10,
      current: 1,
      size: 'small',
      showSizeChanger: true,
      showQuickJumper: true,
    }, // 表格分布数据
    columns: columns, // 表格列信息
    editId: '', // 编辑行id
    selectionIds: [], // 表格选择ID
    selectedRows: [], // 表格选择行
    requiredCols: requiredCols, // 字段校验规则
    moneyModal: false, // 申请费用弹窗
    modalForm: {
      avgFlag: {
        name: 'avgFlag',
        value: 'Z'
      }
    }, // 申请费用表单数据
    moneyRows: moneyRows, // 是请费用表单行
    isDirty: false, // 页面是否有拆单未提交的
    dirtyId: 0, // 正在编辑的订单id
  },

  effects: {
    // 获取分页数据
    *page({ payload }, { call, put }) {
      const res = yield call(splitPage, payload);
      yield put({
        type: 'page_r',
        payload: res,
      });
    },
    *save({ payload }, { call, put }) {
      const res = yield call(splitSave, payload);
      yield put({
        type: 'save_r',
        payload: res,
      });
    },
    /**del({ payload }, { call, put }) {
      const res = yield call(splitDelLn, payload);
      yield put({
        type: 'del_r',
        payload: res
      })
    },*/
    *costOrders({ payload }, { call, put }) {
      const res = yield call(costOrders, payload);
      yield put({
        type: 'costOrders_r',
        payload: res,
      });
    },
    *rollback({ payload }, { call, put }) {
      const res = yield call(rollbackSplit, payload);
      yield put({
        type: 'del_r',
        payload: res,
      });
    },
    *splitReject({ payload }, { call, put }) {
      const res = yield call(splitReject, payload);
      yield put({
        type: 'send_r',
        payload: res,
      });
    },
  },
  reducers: {
    // 新增
    handleAdd(state) {
      const { pageList, pagination } = state;
      let addList = pageList.filter(page => {
        return page.id === 0;
      });
      if (addList.length) {
        message.warning('请提交后再添加！');
        return {
          ...state,
        };
      } else {
        pageList.unshift({ orderId: 0, status: 'ENTRY' });
        const newPagination = {
          pages: pagination.pages,
          pageSize: pagination.pageSize,
          total: pagination.total + 1,
          current: pagination.current,
          size: 'small',
          showSizeChanger: true,
          showQuickJumper: true,
        };
        return {
          ...state,
          pageList: pageList,
          pagination: newPagination,
        };
      }
    },
    handleSplit(state, action) {
      const { pageList, pagination } = state;
      const { id } = action.payload;

      pageList.forEach(pl => {
        if (id === pl.id) {
          let { children } = pl;
          if (!children) {
            children = [];
          }
          children.push({
            id: `${pl.loadNo}|${children.length + 1}`,
            loadNo: `${pl.loadNo}|${children.length + 1}`,
            parentId: pl.id,
            status: pl.status,
            busType: pl.busType,
            carType: pl.carType,
            pickDate: pl.pickDate,
            aogDate: pl.aogDate,
            line: pl.line,
            amount: pl.amount,
            volume: pl.volume,
            weight: pl.weight,
          });
          pl.children = children;
        }
      });
      const newPagination = {
        pages: pagination.pages,
        pageSize: pagination.pageSize,
        total: pagination.total + 1,
        current: pagination.current,
        size: 'small',
        showSizeChanger: true,
        showQuickJumper: true,
      };
      return {
        ...state,
        pageList: pageList,
        pagination: newPagination,
        isDirty: true,
        dirtyId: id,
      };
    },
    // 删除子订单
    handleDel(state, action) {
      const { pageList, pagination } = state;
      const { parentId, loadNo } = action.payload;
      pageList.forEach(p => {
        if (p.id === parentId) {
          p.children.forEach((c, i) => {
            if (c.loadNo === loadNo) {
              p.children.splice(i, 1);
            }
          });
          if (!p.children.length) {
            p.children = null;
          } else {
            for (let i = 0; i < p.children.length; i++) {
              p.children[i].id = `${p.loadNo}|${i + 1}`;
              p.children[i].loadNo = `${p.loadNo}|${i + 1}`;
            }
          }
        }
      });
      const newPagination = {
        pages: pagination.pages,
        pageSize: pagination.pageSize,
        total: pagination.total - 1,
        current: pagination.current,
        size: 'small',
        showSizeChanger: true,
        showQuickJumper: true,
      };
      return {
        ...state,
        pageList: pageList,
        pagination: newPagination,
      };
    },
    // 绑定搜索框数据
    handleSearchChange(state, action) {
      const { searchValues } = state;
      const newSearchForm = {
        ...searchValues,
        ...action.payload,
      };
      return {
        ...state,
        searchValues: newSearchForm,
      };
    },
    // 处理编辑
    handleEdit(state, action) {
      return {
        ...state,
        editId: action.payload,
      };
    },
    // 处理申请费用
    handleMoneyModal(state, action) {
      const { moneyModal, selectedRows } = state;
      let weight = 0;
      let volume = 0;
      selectedRows.forEach(row => {
        let w = row.weight ? row.weight : 0;
        let v = row.volume ? row.volume : 0;
        weight += w;
        volume += v;
      })
      return {
        ...state,
        moneyModal: !moneyModal,
        modalForm: {
          avgFlag: {
            name: 'avgFlag',
            value: 'Z'
          },
          pickFee: {
            name: 'pickFee',
            value: 0
          },
          arteryFee: {
            name: 'arteryFee',
            value: 0
          },
          dropoffFee: {
            name: 'dropoffFee',
            value: 0
          },
          workoverFee: {
            name: 'workoverFee',
            value: 0
          },
          loadupFee: {
            name: 'loadupFee',
            value: 0
          },
          loadoffFee: {
            name: 'loadoffFee',
            value: 0
          },
          carFee: {
            name: 'carFee',
            value: 0
          },
          fuelFee: {
            name: 'fuelFee',
            value: 0
          },
          callbackFee: {
            name: 'callbackFee',
            value: 0
          },
          escortinFee: {
            name: 'escortinFee',
            value: 0
          },
          tipFee: {
            name: 'tipFee',
            value: 0
          },
          shuttleFee: {
            name: 'shuttleFee',
            value: 0
          },
          realWePrice: {
            name: 'realWePrice',
            value: weight
          },
          realVoPrice: {
            name: 'realVoPrice',
            value: volume
          }
        },
      };
    },
    handleSelectDriver(state, action) {
      const { modalForm } = state;
      const { carNo, drPhone, drIdcard, accountName, bankAccount, driver } = action.payload;
      return {
        ...state,
        modalForm: {
          ...modalForm,
          driver: {
            name: 'driver',
            value: driver,
            touched: true,
            dirty: true,
            validating: true,
          },
          carNo: {
            name: 'carNo',
            value: carNo,
            touched: true,
            dirty: true,
            validating: true,
          },
          drPhone: {
            name: 'drPhone',
            value: drPhone,
            touched: true,
            dirty: true,
            validating: true,
          },
          drIdcard: {
            name: 'drIdcard',
            value: drIdcard,
            touched: true,
            dirty: true,
            validating: true,
          },
          accountName: {
            name: 'accountName',
            value: accountName,
            touched: true,
            dirty: true,
            validating: true,
          },
          bankAccount: {
            name: 'bankAccount',
            value: bankAccount,
            touched: true,
            dirty: true,
            validating: true,
          },
        },
      };
    },
    // 费用表单值绑定
    handleModalChange(state, action) {
      const { modalForm } = state;
      const { fields } = action.payload;
      const newModalForm = {
        ...modalForm,
        ...fields,
      };
      return {
        ...state,
        modalForm: newModalForm,
      };
    },

    // 改变分页插件
    handlePagination(state, action) {
      const { payload } = action;
      const { pagination } = state;
      let newPagination = {
        ...pagination,
        ...payload,
      };
      return {
        ...state,
        pagination: newPagination,
      };
    },

    // 保存子单
    handleSaveSplit(state, action) {
      let { record, row } = action.payload;
      const { pageList, pagination } = state;
      const { parentId } = record;

      row = {
        ...row,
        pickDate: row.pickDate.format('YYYY-MM-DD'),
        aogDate: row.aogDate.format('YYYY-MM-DD'),
        status: 'SPLIT',
        parentId: record.parentId,
      };
      pageList.forEach(pl => {
        if (pl.id === parentId) {
          let newChildren = [];
          pl.children.forEach(child => {
            if (child.loadNo === row.loadNo) {
              newChildren.push(row);
            } else {
              newChildren.push(child);
            }
          });
          pl.children = newChildren;
        }
      });
      return {
        ...state,
        editId: '',
        pageList,
        pagination,
        isDirty: false,
      };
    },

    // 表格选中Id
    handleSelection(state, action) {
      const { selectedRowKeys, selectedRows } = action.payload;
      return {
        ...state,
        selectionIds: selectedRowKeys,
        selectedRows: selectedRows,
      };
    },
    // 分页数据请求回来后处理
    page_r(state, action) {
      const { payload } = action;
      if (payload && payload.code === 0) {
        const list = payload.result.records;
        const pagination = {
          pages: payload.result.pages,
          pageSize: payload.result.size,
          total: payload.result.total,
          current: payload.result.current,
          size: 'small',
          showSizeChanger: true,
          showQuickJumper: true,
        };
        return {
          ...state,
          pagination: pagination,
          pageList: list,
          editId: '',
          selectionIds: [],
          selectedRows: [],
          isDirty: false,
        };
      } else {
        return {
          ...state,
        };
      }
    },
    // 处理保存
    save_r(state, action) {
      const { payload } = action;
      if (payload && payload.code === 0) {
        message.success('保存成功！');
      } else {
        message.error('保存失败！');
      }
      return {
        ...state,
        isDirty: false,
        dirtyId: 0,
      };
    },
    // 处理删除
    del_r(state, action) {
      const { payload } = action;
      if (payload && payload.code === 0) {
        message.success('删除成功！');
      } else {
        message.error(`${payload.errorMsg}` ? `${payload.errorMsg}` : '删除失败！');
      }
      return {
        ...state,
      };
    },
    // 处理发送
    send_r(state, action) {
      const { payload } = action;
      if (payload && payload.code === 0) {
        message.success('操作成功！');
      } else {
        message.error(`${payload.errorMsg}` ? `${payload.errorMsg}` : '操作失败！');
      }
      return {
        ...state,
        selectionIds: [],
      };
    },
    //
    costOrders_r(state, action) {
      const { payload } = action;
      if (payload && payload.code === 0) {
        message.success('申请成功！');
      } else {
        message.error(`${payload.errorMsg}` ? `${payload.errorMsg}` : '申请失败！');
      }
      return {
        ...state,
        moneyModal: false,
      };
    },
  },
};
